﻿import re
from datetime import datetime

from google.appengine.ext import db

class Board(db.Model):
    board_id = db.IntegerProperty()
    board_name = db.StringProperty()
    board_name_lowercase = db.StringProperty()
    board_desc = db.StringProperty()
    board_class = db.IntegerProperty()
    board_type = db.IntegerProperty()

class Thread(db.Model):
    thread_id = db.IntegerProperty()
    board_name = db.TextProperty()
    title = db.TextProperty()
    author = db.TextProperty()

class Post(db.Model):
    post_id = db.IntegerProperty()
    board_id = db.IntegerProperty()
    thread_id = db.IntegerProperty()
    post_time = db.DateTimeProperty()
    title = db.TextProperty()
    word_count = db.TextProperty()
    author = db.TextProperty()
    tag = db.TextProperty()

    from_ip = db.TextProperty()
    head = db.TextProperty()
    ref = db.TextProperty()
    signature = db.TextProperty()
    attachment = db.TextProperty()
    content = db.TextProperty()
    created_on = db.DateTimeProperty(auto_now_add = True)

    def toHTML(self, config):
        html = u'<span class="attr">标题:</span><span class="title">'+self.title +u'</span><br>'
        if config:
            if config.showHead:
                html += formatHTML(self.head)
            if config.showPost:
                html += formatHTML(self.content)
            if config.showRef:
                html += formatHTML(self.ref)
            if config.showAttachment:
                html += self.attachment
            if config.showSignature:
                html += formatHTML(self.signature)
        else:
            html += formatHTML(self.head + self.content + self.ref) + self.attachment + formatHTML(self.signature)
        #html = '<div id="'+str(self.board_id)+'_'+str(self.post_id)+'">'+html+'</div>'
        #html = '<div id="posthtml">'+html+'</div>'
        return html

    def toHTMLForViewPoint(self, config):
        html = u'<div class="post">'
        #html = u'<div class="post_info" id="Post_'+str(self.post_id)+u'" onclick="toggleHead(\'Post_'+str(self.post_id)+u"""')">"""+ u'<span class="attr">标题:</span><span class="title">'+self.title +u'</span><br>'
        if config:
            html += u'<div class="head">'
            if config.showTitle:
                html += u'<div class="title"><span class="attr">标题:</span><span class="val">'+self.title +u'</span></div>'
            if config.showSender:
                html += u'<div class="sender"><span class="attr">作者:</span><span class="val">'+self.author +u'</span></div>'
            if config.showDate:
                html += u'<div class="date"><span class="attr">时间:</span><span class="val">'+self.post_time.strftime('%Y-%m-%d %a %H:%M:%S') +u'</span></div>'
            if config.showIP:
                html += u'<div class="ip"><span class="attr">来自:</span><span class="val">'+self.from_ip +u'</span></div>'
            html += u'</div>'
            
            if config.showPost:
                html += u'<div class="content">'+formatHTML(self.content)+u'</div>'
            if config.showRef:
                html += u'<div class="reference">'+formatHTML(self.ref)+u'</div>'
            if config.showAttachment:
                html += u'<div class="attachment">'+self.attachment+u'</div>'
            if config.showSignature:
                html += u'<div class="signature">'+formatHTML(self.signature)+u'</div>'
        else:
            html += formatHTML(self.head) + u'</div><div class="content">' + formatHTML(self.content) + u"</div>" + formatHTML(self.ref) + self.attachment + formatHTML(self.signature)
        
        html += u'</div>'
        
        return html

def formatHTML(text):
    if not text:
        text = ''

    html = text.replace("\\", "").replace("\n", "<br>\n")

    newhtml = html
    
    """
    newhtml = ''
    pattern = '''((ht|f)tp(s?)\:\/\/|~/|/)?([\w]+:\w+@)?([a-zA-Z]{1}([\w\-]+\.)+([\w]{2,5}))(:[\d]{1,5})?((/?\w+/)+|/?)(\w+\.[\w]{3,6})?((\?\w+=\w+)?(&\w+=\w+)*)?'''
    #pattern = '''((((ht|f)tps?):\/\/)?(?:([a-zA-Z\d\-_]+)@?([a-zA-Z\d\-_]+)\:)?((?:(?:(?:(?:[a-zA-Z\d](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?)\.)*([a-zA-Z](?:(?:[a-zA-Z\d]|-)*[a-zA-Z\d])?))|(?:(?:\d+)(?:\.(?:\d+)){3}))(?::(\d+))?)(?:\/((?:(?:(?:[a-zA-Z\d$\-_.+!*'(),~]|(?:%[a-fA-F\d]{2}))|[;:@&=])*)(?:\/(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),~]|(?:%[a-fA-F\d]{2}))|[;:@&=])*))*)(\?(?:(?:(?:[a-zA-Z\d$\-_.+!*'(),~]|(?:%[a-fA-F\d]{2}))|[;:@&=])*))?)?)'''
    match_objs = re.finditer(pattern, html)
    if match_objs:
        pre_end = 0
        for match_obj in match_objs:
            start = match_obj.start()
            end = match_obj.end()
            url_text = html[start:end]

            url = ''
            if re.search('''^(ht|f)tp(s?)\:\/\/''', url_text) is None:
                url = 'http://'+url_text
            else:
                url = url_text

            newhtml = newhtml + html[pre_end:start]+'<a href="'+url+'" target="_blank">'+url_text+'</a>'
            pre_end = end

        newhtml = newhtml +html[pre_end:]
    else:
        newhtml = html
    """
    
    return newhtml

def cleanOldPosts(count=100):
    q = db.GqlQuery("SELECT * FROM Post ORDER BY created_on")
    results = q.fetch(count)
    db.delete(results)

class Style(db.Model):
    id = db.IntegerProperty()
    email = db.StringProperty()
    content = db.TextProperty()
    last_update = db.DateTimeProperty(auto_now = True)
    
class Configuration(db.Model):
    user = db.UserProperty()
    showTitle = db.BooleanProperty()
    showHead = db.BooleanProperty()
    showPost = db.BooleanProperty()
    showRef = db.BooleanProperty()
    showSignature = db.BooleanProperty()
    showAttachment = db.BooleanProperty()
    
    showSender = db.BooleanProperty()
    showDate = db.BooleanProperty()
    showIP = db.BooleanProperty()
    

    showThreadNewPage = db.BooleanProperty()
    showThreadOriginUrl = db.BooleanProperty()
    threads_count = db.IntegerProperty()
    boards_count = db.IntegerProperty()
    posts_count = db.IntegerProperty()
    created_on = db.DateTimeProperty(auto_now_add = True)
    last_update = db.DateTimeProperty(auto_now = True)
